'''点餐屏订单处理模块'''

# 1、获取订单
# 2、更新订单状态
import time,json,requests
from configs import parse_args
# -- coding: utf-8 --**
import requests
import json
import copy
from configs import logger
import time
from datetime import datetime

class HttpOrder:
    def __init__(self):
        self.parse = parse_args()
        self.url = self.parse.get_order_url
        self.shop_id = self.parse.shop_id
        self.updataurl = self.parse.update_order_url
        self.shop_serial = self.parse.shop_serial
        self.current_order = {}
        self.oldordrlist = []
        self.current_order_len=0

    def get_data(self):
        param = {"shop_serial":self.shop_serial}
        data = json.loads(requests.get(url=self.url, params=param,timeout=25).text)
        # data = {'code': 0, 'msg': 'ok', 'data': {
        #     "work_order_number": "W2023092300003",
        #     "work_order_seal_state": "no",
        #     "work_order_type": 1,
        #     "is_noodle_press": 1,
        #     "work_order": [
        #         {
        #             "toppings": {
        #                 "device_no": "1",
        #                 "device_type": "1",
        #                 "num": "1",
        #                 "serial": "A136"
        #             },
        #             "meal_number":"CLK124",
        #             "meal_name":"宫保鸡丁",
        #             "meal_info": [],
        #             "is_noodle_product": "1",
        #             "is_shp_property": "1",
        #             "is_add_soup": "1",
        #             "is_topping": "0",
        #             "topping_heating": "1",
        #             "topping_add_soup_time": "5",
        #             "topping_fire": "0",
        #             "topping_heating_time": "60",
        #             "is_guoshui": "1",
        #             "guoshui_time": "3",
        #             "shp_property_type": "2"
        #         },
        #         {
        #             "toppings": {
        #                 "device_no": "1",
        #                 "device_type": "1",
        #                 "num": "1",
        #                 "serial": "A136"
        #             },
        #             "meal_number":"CLK124",
        #             "meal_name":"宫保鸡丁",
        #             "meal_info": [],
        #             "is_noodle_product": "1",
        #             "is_shp_property": "1",
        #             "is_add_soup": "1",
        #             "is_topping": "0",
        #             "topping_heating": "1",
        #             "topping_add_soup_time": "5",
        #             "topping_fire": "0",
        #             "topping_heating_time": "60",
        #             "is_guoshui": "1",
        #             "guoshui_time": "3",
        #             "shp_property_type": "2"
        #         }

        #     ]
        # }
        # }
        if data["code"] !=0:
            return {"data":[]}
        return data                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    def get_order(self):
        while True:
            time.sleep(1)
            try:
                httpdata = self.get_data()#
            except Exception as e:
                logger.info(str(e))
                logger.info("HTTP connect fail")
            else:
                if bool(httpdata["data"]):

                    if httpdata["data"]["work_order_number"] not in self.oldordrlist:
                        # self.current_order = httpdata["data"]
                        self.format_current_order(httpdata["data"])
                        self.oldordrlist.append(httpdata["data"]["work_order_number"] )
                        # self.updata_statu(self.work_order_number,"2")
                        logger.info(".............get order .............")
                        logger.info(httpdata["data"])
                        # print(self.current_order)
                        # print(list(self.current_order.values())[0])
                        

    def format_current_order(self,order):
        if bool(order):
            uuid = order["work_order_number"]
            name_number = []
            self.current_order_len = len(order["work_order"])
            for work_order in order["work_order"]:
                            #不匹配的直接报完成
                meal_name = work_order["meal_name"]
                meal_number = work_order["meal_number"]
                name_number.append((meal_number,meal_name))
                # if int(work_order["shp_property_type"]):#取料柜取浇头
                #     # if int(work_order["shp_property_type"]):
                #     # self.logger.info("订单{}:出面,取浇头".format(uuid))
                #     # noodle_channel =work_order["toppings"]["device_no"] if len(work_order["toppings"]) else 0#取面货到号
                #     if len(work_order["toppings"]):
                #         if isinstance(work_order["toppings"],list):
                #             noodle_channel =work_order["toppings"][0]["device_no"]
                #         elif isinstance(work_order["toppings"],dict):
                #             noodle_channel =work_order["toppings"]["device_no"]
                #         else:noodle_channel=0
                #     else:
                #         noodle_channel=0
                # else:#不取浇头
                #     # if int(work_order['is_noodle_product']):
                #     #     noodle_channel = 0
                #     # else:
                #     logger.info("不匹配原料，直接更新")
                #     # self.updata_statu(uuid,1)
                #     self.updata_statu(uuid,2)
                #     self.updata_statu(uuid,3)
                #     self.updata_statu(uuid,4)
                #     return 0,0
                #     # self.logger.info("订单{}:出面,不取浇头".format(uuid))
                # is_add_soup =work_order["is_add_soup"]#是否加汤
                # # is_add_noodle =work_order["is_add_noodle"]#是否加面
                # # add_noodle_channel =work_order["add_noodle_channel"]#加面货到号
                # cook_time =work_order["meal_info"]["mealproperty"]["hardness"]["cooked_time"] if len(work_order["meal_info"])  and "hardness" in work_order["meal_info"]["mealproperty"].keys() else 0#煮面时间
                # #Y1宽面，Y2细面
                # noodle_type =work_order["meal_info"]["mealproperty"]["hardness"]["serial"] if len(work_order["meal_info"])  and "hardness" in work_order["meal_info"]["mealproperty"].keys() else 'Y0'#面条类型
                # is_guoshui= work_order["is_guoshui"] #是否过水
                # guoshui_time= work_order["guoshui_time"]#过水时间
                # topping_heat_time = work_order["topping_heating_time"]#浇头加热时间
                # cook_times.append(int(cook_time))
                # guoshui_times.append(int(guoshui_time))
                # noodle_channels.append(noodle_channel) if noodle_channel else 0
                # is_guoshuis.append(int(is_guoshui))
                # is_add_soups.append(int(is_add_soup))
                # noodle_types.append(int(noodle_type[-1]))#1是正常面，2是细面
                # topping_heat_times.append(int(topping_heat_time))

            self.current_order[uuid] = name_number
            # return uuid,noodle_channels

    def updata_statu(self,order_number,state,serial="D1", max_retry: int = 5):
        retry_count = 0
        while retry_count < max_retry:
            param = {
                "shop_serial": self.shop_serial,
                "order_number": order_number,
                "state": state,
                "serial": serial
            }
            try:
                response = requests.get(self.updataurl, params=param, timeout=10)
                data = response.json()
            except Exception as e:
                logger.warning(f"[{retry_count + 1}/{max_retry}] 网络异常：{order_number}:{state}，错误：{e}")
            else:
                if data.get('code') == 0:
                    logger.info(f"订单状态更新成功：{order_number}:{state}")
                    return True
                else:
                    logger.warning(f"[{retry_count + 1}/{max_retry}] 更新失败：{order_number}:{state}，返回：{data}")
            retry_count += 1
            time.sleep(3)

        logger.error(f"🚨 最终订单状态更新失败：{order_number}:{state}，共尝试 {max_retry} 次")


    #故障上报与更新
    def update_fault(self,error_type:str,error_code:int,cause:str):
        while True:
            if error_type == "1":#上报故障
                error_data = {"shop_serial":self.shop_serial,"type":error_type,"cause":cause,"fault_time":datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S'),"level":"2"}
                pass
            if error_type == "2":#清除故障
                error_data = {"shop_serial":self.shop_serial,"type":error_type,"recovery_time":datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')}
                pass
            try:
                # logger.info(error_data)
                data = json.loads(requests.get(self.parse.update_fault, params=error_data,headers={"Content-Type":"application/json"},timeout=25).text)
                # logger.info(error_data,data)
            except:
                logger.info("网络异常，故障上报与更新失败，尝试重新更新...")
                time.sleep(5)
                # self.update_fault(error_type,error_code,cause)
            else:
                if data['code']==0:
                    # logger.debug(data)
                    # logger.debug("更新成功：用餐排队进度")
                    break
                else:
                    logger.debug("故障上报与更新失败")
                    logger.debug("异常：（故障上报与更新失败）：{}".format(data["message"]))
if __name__ == "__main__":
    httporder = HttpOrder()
    uuid = 'W2025041700006'
    httporder.updata_statu(uuid,2)
    httporder.updata_statu(uuid,3)
    httporder.updata_statu(uuid,4)
    # httporder.get_order()
    # httporder.format_current_order()